import { List, fromJS } from "immutable";
import { Action } from "redux";
import {
    MAP_LOADING, MAP_READY,
    MAP_ROLL_START, MAP_ROLLING, MAP_ROLL_STOP,
    MAP_LINE_BLANK, MAP_LINE_FILL,
    MAP_COLS, MAP_ROWS
} from "../constants/MapConst";
import { MapAction } from "../actions";

const mapInit = () => {
    let martrix: List<List<number>> = List.of();
    for (let i = 0; i < MAP_ROWS; i++) {
        // let lstCols: List<number> = List.of();
        // for (let j = 0; j < MAP_COLS; j++) {
        //     lstCols = lstCols.set(j, 0);
        // }
        martrix = martrix.set(i, MAP_LINE_BLANK);
    }
    return martrix;
};

const mapLoad = (inData: List<List<number>>, inFrom: number) => {
    if (inFrom === 0) {
        for (let y = MAP_ROWS - 1; y >= 0; y--) {
            if (inData.get(y).get(0) === 0) {
                inData = inData.set(y, MAP_LINE_FILL);
                break;
            }
        }
    } else {
        for (let y = 0; y < MAP_ROWS; y++) {
            if (inData.get(y).get(0) === 1) {
                inData = inData.set(y, MAP_LINE_BLANK);
                break;
            }
        }
    }
    return inData;
};

const downRolling = (inData: List<List<number>>, inShape: string, coordinate: Game.ICoordinate) => {
    return {
        data: List([]),
        coordinate: { x: coordinate.x, y: coordinate.y + 1 }
    };
};

const initialState = fromJS({
    status: "NONE",
    cols: MAP_COLS,
    rows: MAP_ROWS,
    coordinate: { x: 0, y: 0 },
    data: mapInit(),
});

const mapReducer = (state = initialState, action: Action & { payload: any }) => {
    const { type, payload } = action;
    switch (type) {
        case MAP_READY:
            return state.merge({
                status: "Ready"
            });
        case MAP_LOADING:
            return state.merge({
                status: "RollReady",
                data: mapLoad(payload.data, payload.from)
            });
        case MAP_ROLL_START:
            return state.set("status", "Rolling");
        case MAP_ROLLING:
            const result = downRolling(payload.data, payload.shape, payload.coodrinate);
            return state.merge({
                coordinate: result.coordinate,
                data: result.data
            });
        case MAP_ROLL_STOP:
            return state.set("status", "Stopped");
        default:
            return state;
    }
};

export default mapReducer;
